import { getChildData, getStaticDataList } from '../../designer/webServer/services';
import type { inbiz } from '@inbiz/core';
import { getMessage } from '@inbiz/react';
import { getListGroupIds } from '../../designer/wapServer/service';
import { useInbizData, IAPI } from '@inbiz/hooks';
import { ReactNode } from 'react';
export interface IBaseEformStaticList {
  callBackEvents?: {
    onParamFormat?: (param: { appId: string; groupKey: string }) => {
      appId: string;
      groupKey: string;
    };
    onRequest?: (parm: any) => Promise<any>;
    onData?: (
      data: {
        Value: string;
        Text: string;
      }[],
    ) => object[];
  };
  inbiz: inbiz;
  label?: string;
  defaultValue?: string;
  value?: any;
  selectMode?: boolean;
  showMode?: number;
  labelDirection?: number;
  layoutMode?: string;
  placeholder?: string;
  dataGroupId?: string | object;
  className?: string;
  disabled?: boolean;
  readOnly?: boolean;
  autoLoading?: boolean;
  selectHeight?: number;
  childModelConfig: boolean;
  dataType?: 'system' | 'custom';
  componentIsInline?: boolean;
  showField?: string;
  storageConfig?: {
    business: string;
    tableData: {
      id: number;
      modelAttr: string;
      componentAttr: string;
    }[];
  };
  controlId?: string;
  disabledOptions: string[];
  hideDisabledOptions: boolean;
  onClick?: (e: any) => void;
  onChange?: (v: any | any[]) => void;
}

// 默认值转换

export const defaultValueFormat = async (
  props: IBaseEformStaticList,
): Promise<string | void | string[]> => {
  let arr = [];
  if (props.defaultValue) {
    if (props.dataType != 'custom') {
      arr = Array.isArray(props.defaultValue) ? props.defaultValue : props.defaultValue?.split(',');
      if (arr.length) {
        const data = {
          appId: props.inbiz?.appInfo?.appId,
          groupKey: props.dataGroupId,
        };
        let res = await getStaticDataList(data as any);
        if (Array.isArray(res)) {
          let newArr: any[] = [];
          arr.map((item: string) => {
            res.map((val: any) => {
              item === val.Value && newArr.push(item);
            });
          });
          if (props.selectMode) {
            return newArr;
          } else if (newArr.length) {
            return newArr[0];
          }
        }
      } else {
        const value = Array.isArray(props.defaultValue)
          ? props.defaultValue
          : props.defaultValue?.split(',');
        return props.selectMode ? value : value[0];
      }
    } else {
      const value = props.defaultValue;
      if (props.selectMode) {
        return Array.isArray(value) ? value : value.split?.(',');
      } else {
        return value;
      }
    }
  }
};

// 回显转换
export const originValueFormat = (value: any, props: IBaseEformStaticList) => {
  if (props.childModelConfig && props.storageConfig && props.dataType === 'system') {
    return getChildData(props).then((res) => {
      if (res?.data?.length) {
        let modelAttr = props.storageConfig?.tableData.filter(
          (item: any) => item.componentAttr == 'value',
        )[0].modelAttr;
        if (modelAttr) {
          let data = res?.data.map((item: any) => item[modelAttr!]);
          return props.selectMode ? data : data[0];
        }
      } else {
        if (props.selectMode) {
          return Array.isArray(value) ? value : value.split?.(',');
        } else {
          return value;
        }
      }
    });
  } else {
    if (props.selectMode) {
      return Array.isArray(value) ? value : value.split?.(',');
    } else {
      return value;
    }
  }
};

const getGroupIdsList = (() => {
  let groupIds: [string, Function, Function][] = [];
  return (appId: string, groupId: string) => {
    return new Promise((resolve, reject) => {
      groupIds.push([groupId, resolve, reject]);
      const timer = setTimeout(() => {
        const newGroupIds = groupIds;
        groupIds = [];
        if (newGroupIds.map((item) => item[0]).join(',').length > 0) {
          getListGroupIds({ appId, groupIds: newGroupIds.map((item) => item[0]).join(',') })
            .then((res) => {
              newGroupIds.forEach(([id, itemResolve]) => {
                let list = getListData(id, res);
                itemResolve(list);
              });
            })
            .catch((e) => {
              reject(e);
              newGroupIds.forEach(([id, itemResolve, itemReject]) => {
                itemReject(e);
              });
            });
        }
        clearTimeout(timer);
      }, 100);
    });
  };
})();

const getListData = (groupId: string, groupIdsList: object) => {
  let list: object[] = [];
  if (groupIdsList) {
    Object.keys(groupIdsList).forEach((item) => {
      if (item == groupId) {
        list = groupIdsList[item].map((item1: { Text: string; Value: string }) => ({
          label: getMessage(item1.Text),
          value: item1.Value,
        }));
      }
    });
  }
  return list;
};

// pc、移动端公共请求数据hooks
type IOption = {
  label: string;
  value: string | number;
  disabled?: boolean;
};
export function useRequestData(props: IBaseEformStaticList, configEvents: any) {
  return useInbizData(
    () => {
      if (props.dataType === 'system' || props.dataType === undefined) {
        return {
          service: (data: { appId: string; groupKey: string }) => {
            if (data.groupKey) {
              return getGroupIdsList(data.appId, data.groupKey);
            } else {
              return Promise.resolve([]);
            }
          },
        };
      } else {
        if (props.dataGroupId && typeof props.dataGroupId === 'object') {
          if (props.dataGroupId['modelKey']) {
            return { modelkey: props.dataGroupId['modelKey'] as string };
          } else {
            return props.dataGroupId as IAPI;
          }
        } else {
          return;
        }
      }
    },
    {
      initialData: [],
      configEvents,
      formatResult: ({ data }: any): IOption[] => {
        if (data && typeof data == 'object') {
          const primaryKey =
            props.dataGroupId?.['primaryKey'] ||
            (props.dataGroupId as unknown as IAPI)?.result?.primaryKey || 'value';
          if (data?.['Rows']?.length && primaryKey) {
            (data?.['Rows'] as { value?: unknown; label: string | ReactNode }[]).forEach((item) => {
              item.value = item[primaryKey]?.toString();
              item.label = item[props.showField || 'label'];
            });
          }
          return Array.isArray(data) ? data : (data['Rows'] as IOption[]) || [];
        } else {
          return [] as IOption[];
        }
      },
    },
  );
}
